"""
CORS配置模块
提供跨域资源共享的配置选项
"""

from typing import List
import os

# 开发环境允许的源
DEV_ORIGINS = [
    "http://localhost:3000",      # React开发服务器
    "http://localhost:8080",      # Vue开发服务器
    "http://localhost:5262",      # Angular开发服务器
    "http://127.0.0.1:3000",
    "http://127.0.0.1:8080",
    "http://127.0.0.1:4200",
    "http://localhost:8088",      # FastAPI服务器本身
    "http://127.0.0.1:8088",
]

# 生产环境允许的源（请根据实际情况修改）
PROD_ORIGINS = [
    "https://market.huixiangwuyou.com",
    "https://next.huixiangwuyou.com",
    "http://localhost:3000",      # React开发服务器
    "https://yourdomain.com",
    "http://localhost:5262",      # Angular开发服务器
    "http://localhost:8088",      # FastAPI服务器本身
    "https://api.yourdomain.com",
]

# 允许的HTTP方法（确保包含所有RESTful方法）
ALLOWED_METHODS = [
    "GET",
    "POST", 
    "PUT",
    "DELETE",
    "PATCH",
    "OPTIONS",
    "HEAD"
]

# 允许的请求头（增加更多常用头部）
ALLOWED_HEADERS = [
    "Accept",
    "Accept-Encoding",
    "Accept-Language",
    "Content-Language",
    "Content-Type",
    "Authorization",
    "X-Requested-With",
    "X-CSRF-Token",
    "X-API-Key",
    "Cache-Control",
    "Pragma",
    "Expires",
    "Origin",
    "Referer",
    "User-Agent",
    "X-Forwarded-For",
    "X-Real-IP"
]

def get_cors_config():
    """
    获取CORS配置
    
    Returns:
        dict: CORS配置字典
    """
    # 根据环境变量确定当前环境
    # environment = os.getenv("ENVIRONMENT", "production").lower()
    #
    # if environment == "production":
    #     origins = PROD_ORIGINS
    # else:
    #     # 开发环境允许所有源（不推荐用于生产）
    #     origins = ["*"]
    origins = PROD_ORIGINS
    print("允许的源：", origins)
    return {
        "allow_origins": origins,
        "allow_credentials": True,
        "allow_methods": ALLOWED_METHODS,
        "allow_headers": ALLOWED_HEADERS,
        "expose_headers": [
            "Content-Length",
            "Content-Range",
            "X-Total-Count"
        ],
        "max_age": 86400,  # 预检请求缓存时间（秒）
    }

def get_cors_middleware_config():
    """
    获取CORS中间件配置
    
    Returns:
        dict: 可以直接传递给CORSMiddleware的配置
    """
    config = get_cors_config()
    
    
    # 如果允许所有源，需要特殊处理
    if config["allow_origins"] == ["*"]:
        print("警告：使用通配符允许所有源，将禁用凭据")
        return {
            "allow_origins": ["*"],
            "allow_credentials": False,  # 当allow_origins为["*"]时，credentials必须为False
            "allow_methods": config["allow_methods"],
            "allow_headers": config["allow_headers"],
            "expose_headers": config["expose_headers"],
            "max_age": config["max_age"],
        }
    
    return config 